package com.zt.rongda.customer.service;

import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.rongda.customer.inter.CustomerMapper;
import com.zt.rongda.customer.model.Customer;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;

@Service
public class CustomerService extends BaseService {

    @Autowired
    private CustomerMapper customerMapper;

    /**
    * 查询
    *
    * @param reqBean
    * @return
    */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from CUSTOMER where 1=1 ");
        if(StringUtil.isNotEmpty(reqBean.getInfo("customerName"))){
            sqlBuilder.addWhereLike2("CUSTOMER_NAME", reqBean.getInfo("customerName"));
        }
        sqlBuilder.orderBy(" ORDER BY CUSTOMER_NAME");
        
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }
    
    public JSONArray getList() {
        SqlBuilder sqlBuilder = new SqlBuilder("select * from CUSTOMER ORDER BY CUSTOMER_NAME");
        return query(sqlBuilder);
    }

    /**
    * 通过id查询
    *
    * @param customerId
    * @return
    */
    public Customer getById(String customerId) {
        return customerMapper.selectByPrimaryKey(customerId);
    }

    /**
    * 新增
    *
    * @param customer
    */
    public void add(Customer customer) {
        customer.setCustomerId(stringId());// 手动设置Id

        customer.setMakeTime(new Date());
        customer.setModifyTime(customer.getMakeTime());
        customerMapper.insert(customer);
    }

    /**
    * 修改
    *
    * @param customer
    */
    public void update(Customer customer) {
        String customerId = customer.getCustomerId();
        if (StringUtil.isEmpty(customerId)) {
            throw new BusinessException("获取主键失败");
        }

        customer.setModifyTime(new Date());
        customerMapper.updateByPrimaryKeySelective(customer);
    }

    /**
    * 删除
    *
    * @param customerId
    */
    public void delete(String customerId) {
        if (StringUtil.isEmpty(customerId)) {
            throw new BusinessException("获取主键失败");
        }
        
        if(hasOrder(customerId)){
            throw new BusinessException("当前客户关联订单信息，不能删除!");
        }else{
            customerMapper.deleteByPrimaryKey(customerId);
        }
    }
    
    private boolean hasOrder(String customerId){
        //TODO 查询有无订单
        return false;
    }

}